package io.github.quickmsg.common.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static java.util.Objects.requireNonNull;

/**
 *
 */
public class MyInboundIdleStateHandler extends IdleStateHandler {

    private final Consumer<IdleState> onReadIdle;

    public MyInboundIdleStateHandler(long idleTimeout, Consumer<IdleState> onReadIdle) {
        super(idleTimeout, 0, 0, TimeUnit.MILLISECONDS);
        this.onReadIdle = requireNonNull(onReadIdle, "onReadIdle");
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx,
                               IdleStateEvent evt) throws Exception {
        if (evt.state() == IdleState.READER_IDLE) {
            onReadIdle.accept(evt.state());
        }
        super.channelIdle(ctx, evt);
    }
}
